package tcp_ip_socket;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.net.SocketException;

/**
 * @version: 1.0
 * @Description: TODO
 * @author: zZmH
 * @date: 2020/10/05 22:54
 */


public class TCPEchoClient {
    public static void main(String[] args) throws IOException {
        String server = "127.0.0.1";
        int port = 7;
        byte[] data = server.getBytes();
        Socket socket = new Socket(server, port);
        InputStream in = socket.getInputStream();
        OutputStream out = socket.getOutputStream();
        out.write(data);
        int totalBytesRcvd = 0;
        int bytesRcvd;
        while (totalBytesRcvd < data.length) {
            if ((bytesRcvd = in.read(data, totalBytesRcvd, data.length - totalBytesRcvd)) == -1) {
                throw new SocketException("Connection closed prematurely");
            }
            totalBytesRcvd += bytesRcvd;
        }System.out.println("Received: " + new String(data));
        socket.close();

    }
}
